#!/bin/python

# --------------------------------------
# VIDEO BUDDHA - main window
# --------------------------------------
# Ranames files based on a specific regex pattern in 
#  show_list.db and based on a specific list of file 
#  extensions.
# --------------------------------------

import sys
import wx

import models.database
import models.renamer
import models.nfo_tv

import views.dia_choose_show
import views.win_about
import views.win_edit_defs
import views.win_edit_options

class WinMain(wx.Frame):
	
	def __init__(self):
		wx.Frame.__init__(self, None, wx.ID_ANY, u"Video Buddha", wx.DefaultPosition, wx.Size(600, 300), wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
		
		# Class declarations
		self.rnm = models.renamer.Renamer()
		self.db  = models.database.Database()
		self.nfo_tv = models.nfo_tv.NFO_TV()
		
		# Application icon
		favicon = wx.Icon('res/favicon.ico', wx.BITMAP_TYPE_ICO, 16, 16)
		self.SetIcon(favicon)
		
		self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)
		
		sizer_top = wx.BoxSizer(wx.VERTICAL)
		
		self.panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
		sizer_main = wx.BoxSizer(wx.VERTICAL)
		
		# List control
		self.list_ctrl = wx.ListCtrl(self.panel, size = (-1, -1), style = wx.LC_REPORT | wx.BORDER_SUNKEN)
		sizer_main.Add(self.list_ctrl, 1, wx.ALL|wx.EXPAND, 5)
		self.list_ctrl.InsertColumn(1, 'File', wx.LIST_AUTOSIZE_USEHEADER, 270)
		self.list_ctrl.InsertColumn(2, 'Rename To', wx.LIST_AUTOSIZE_USEHEADER, 275)
		
		# Browse sizer
		sizer_browse = wx.BoxSizer(wx.HORIZONTAL)
		sizer_main.Add(sizer_browse, 0, wx.ALL | wx.EXPAND, 0)
		
		# Directory chooser
		self.dir_picker = wx.DirPickerCtrl(self.panel, wx.ID_ANY, wx.EmptyString, u"Select a folder", wx.DefaultPosition, wx.DefaultSize, wx.DIRP_DEFAULT_STYLE)
		button_rename = wx.Button(self.panel, wx.ID_ANY, u"Rename Files", size = (100, -1))
		sizer_browse.Add(self.dir_picker, 1, wx.ALL | wx.EXPAND, 5)
		sizer_browse.AddSpacer((10, 0), 0, wx.EXPAND, 5)
		sizer_browse.Add(button_rename, 0, wx.ALL | wx.EXPAND, 5)
		
		self.panel.SetSizer(sizer_main)
		self.panel.Layout()
		sizer_main.Fit(self.panel)
		sizer_top.Add(self.panel, 1, wx.EXPAND |wx.ALL, 0)
		
		self.SetSizer(sizer_top)
		self.Layout()
		self.statusBar = self.CreateStatusBar(1, wx.ST_SIZEGRIP, wx.ID_ANY)
		
		# Menu bar
		self.menubar = wx.MenuBar(0)
		
		# File menu
		self.menu_file = wx.Menu()
		self.menubar.Append(self.menu_file, u"File" )
		
		# File -> Browse
		self.menu_file_browse = wx.MenuItem(self.menu_file, wx.ID_ANY, u"Browse", u"Browse for your video files", wx.ITEM_NORMAL )
		self.menu_file.AppendItem(self.menu_file_browse)
		
		# File -> Refresh
		self.menuItemRefresh = wx.MenuItem(self.menu_file, wx.ID_ANY, u"Refresh Listing", u"Refresh the file listing", wx.ITEM_NORMAL )
		self.menu_file.AppendItem(self.menuItemRefresh)
		
		self.menu_file.AppendSeparator()
		
		# File -> Exit
		self.menu_file_exit = wx.MenuItem(self.menu_file, wx.ID_ANY, u"Exit", u"Exit the program", wx.ITEM_NORMAL)
		self.menu_file.AppendItem(self.menu_file_exit)
		
		# Edit menu
		self.menu_edit = wx.Menu()
		self.menubar.Append(self.menu_edit, u"Edit")
		
		# Edit -> Definitions
		self.menu_edit_defs = wx.MenuItem(self.menu_edit, wx.ID_ANY, u"Definitions", u"Edit definitions for renaming files", wx.ITEM_NORMAL)
		self.menu_edit.AppendItem(self.menu_edit_defs)
		
		# Edit -> Options
		self.menu_edit_options = wx.MenuItem(self.menu_edit, wx.ID_ANY, u"Options", u"Edit configuration options", wx.ITEM_NORMAL)
		self.menu_edit.AppendItem(self.menu_edit_options)
		
		# Help menu
		self.menu_help = wx.Menu()
		self.menubar.Append(self.menu_help, u"Help")
		
		# Help -> About
		self.menu_help_about = wx.MenuItem(self.menu_help, wx.ID_ANY, u"About", u"About Video Renamer", wx.ITEM_NORMAL)
		self.menu_help.AppendItem(self.menu_help_about)
		
		self.SetMenuBar(self.menubar)
		
		self.Centre(wx.BOTH)

		default_dir = self.db.get_option('prev_dir')[1]
		
		# Set the dir from the config
		if self.db.get_option('b_remember_dir')[1]:
			self.dir_picker.SetPath(default_dir)
			self.update_list_ctrl(default_dir)
		
		# Connect Events
		self.Bind(wx.EVT_DIRPICKER_CHANGED, self.on_dir_changed, self.dir_picker)
		self.Bind(wx.EVT_MENU, self.on_browse, self.menu_file_browse)
		self.Bind(wx.EVT_MENU, self.OnExit, self.menu_file_exit)
		self.Bind(wx.EVT_MENU, self.on_edit_defs, self.menu_edit_defs)
		self.Bind(wx.EVT_MENU, self.on_edit_options, self.menu_edit_options)
		self.Bind(wx.EVT_MENU, self.on_about, self.menu_help_about)
		self.Bind(wx.EVT_MENU, self.on_refresh, self.menuItemRefresh)
		self.Bind(wx.EVT_BUTTON, self.on_rename, button_rename)
		self.Bind(wx.EVT_CLOSE, self.OnExit)
	
	def __del__(self):
		self.Destroy()
		sys.exit(0)

	def OnExit(self, event):
		self.Destroy()
		sys.exit(0)
		
	def on_refresh(self, event):
		self.update_list_ctrl(self.db.get_option('prev_dir')[1])
	
	def on_dir_changed(self, event):
		dir = self.dir_picker.GetPath()

		self.db.update_option('prev_dir', dir)
		
		self.update_list_ctrl(dir)
		self.list_ctrl.RefreshItems(0, 100)
		
	def update_list_ctrl(self, dir):
		if self.rnm.path_exists(dir):
			self.list_ctrl.DeleteAllItems()

			self.rnm.set_dir(dir)
			
			# Get the file listing where the file match the given
			#  file extensions
			fileList = self.rnm.get_video_list()
			renameList = self.rnm.get_rename_list()
			
			index = 0
				
			# Run through ALL the files in the directory
			for (dir, file) in fileList:
				self.list_ctrl.InsertStringItem(index, file)
				
				# Find matches and place them in the 'rename to' column
				for (file_old, file_renamed) in renameList:
					if file_old == file:
						self.list_ctrl.SetStringItem(index, 1, file_renamed)

				# Alt row colors
				if index % 2:
					self.list_ctrl.SetItemBackgroundColour(index, wx.Colour(224, 224, 255))
				
				# Iterate that shit
				index += 1
	
	def on_rename(self, event):
		dir = self.dir_picker.GetPath()
		
		if self.rnm.path_exists(dir) == False:
			# Directory doesn't exist or wasn't set
			self.statusBar.SetStatusText("Error: Choose a directory.", 0)
			wx.Bell()
			
		else:
			# Update the status bar with what happened
			#  videos either renamed or, none matched
			self.rnm.set_dir(dir)
			
			# Reset the last show title, not needed?
			self.db.update_option('last_show', 'last_show_text')
			
			videos = self.rnm.get_rename_list()
			count = 0
			for (file_old, file_renamed) in videos:
				#self.rnm.rename_file(dir, file_old, file_renamed)
				
				dir_title_and_file = self.rnm.get_title(dir, file_old)
				seasep_and_trail = self.rnm.get_seasep_trail(dir_title_and_file)
				
				# Title is searched for
				title = seasep_and_trail[2]			
				
				last_show = self.db.get_option('last_show')[1]
				b_write_nfo = self.db.get_option('b_write_nfo')[1]
				
				if int(b_write_nfo) == 1 and last_show != title:
					shows = self.nfo_tv.find_shows(dir, file_old, file_renamed)					
					
					self.create_shows_window(shows, title, self.db)
					
					show    = self.db.get_option('last_show')[1]
					show_id = self.db.get_option('last_show_id')[1]
					
					self.statusBar.SetStatusText(str(show) + " has been selected from theTVDB.", 0)
					
					self.nfo_tv.write_nfo(
					
				count += 1
			
			if count == 0:
				self.statusBar.SetStatusText("Alert: No files were renamed.", 0)
				wx.Bell()
			
			if count > 0:				
				self.statusBar.SetStatusText(str(count) + " file(s) renamed.", 0)
				
		self.update_list_ctrl(dir)
	
	def on_browse(self, event):
		event.Skip()
	
	def on_edit_defs(self, event):
		window_edit_defs = views.win_edit_defs.WinEditDefs()
		window_edit_defs.Show()

		self.update_list_ctrl(self.db.get_option('prev_dir')[1])	
		
	def on_edit_options(self, event):
		window_edit_options = views.win_edit_options.WinEditOptions()
		window_edit_options.Show()
	
	def on_about(self, event):	
		window_about = views.win_about.WinAbout()
		window_about.Show()
		
	def create_shows_window(self, shows, title, db_conn):
		# Create the choose shows dialogue
		dialog_choose_show = views.dia_choose_show.DiaChooseShow(shows, title, db_conn)
		dialog_choose_show.ShowModal()
		dialog_choose_show.Destroy()
			